<script setup lang="ts">
import { Star, StarFilled } from "@element-plus/icons-vue";
import axios from "axios";
import { ElButton, ElIcon, ElMessage } from "element-plus";
import { computed, onMounted, ref, watch } from "vue";
import { router } from "../router";
import { useLogging } from "../stores/logging";
import { BorrowStatusTitle, type BorrowRecord } from "../types/BorrowRecord";
import type { FavoriteRecord } from "../types/FavoriteRecord";
import type { ResultContext } from "../types/ResultContext";

const logging = useLogging();
const user = computed(() => logging.getUser);

/** 获取当前用户的昵称。 */
const displayName = computed(() => {
  return user.value?.nickname ?? user.value?.username ?? "未登录用户";
});

/** 获取当前用户的用户名。 */
const displayUsername = computed(() => {
  return user.value?.username ? `@${user.value?.username}` : "";
});

/** 获取当前用户的会员状态。 */
const isMember = ref(true);

/** 当前借阅列表。 */
const borrows = ref<BorrowRecord[]>([]);

/** 当前收藏列表。 */
const favorites = ref<FavoriteRecord[]>([]);

/** 本地收藏状态映射，用于临时存储取消收藏的状态 */
const localFavoriteStatus = ref<Map<number, boolean>>(new Map());

/** 过滤后的借阅列表，只显示状态不为RETURNED的记录 */
const activeBorrows = computed(() => {
  return borrows.value.filter(record => record.status !== "RETURNED");
});

/** 检查某个收藏项是否处于收藏状态 */
const isFavorited = (favoriteId: number) => {
  // 如果本地状态存在，使用本地状态；否则默认为true（因为在收藏列表中）
  return localFavoriteStatus.value.has(favoriteId)
    ? localFavoriteStatus.value.get(favoriteId)
    : true;
};

/** 计算实际的收藏数量（只计算仍处于收藏状态的项目） */
const actualFavoriteCount = computed(() => {
  return favorites.value.filter(fav => isFavorited(fav.id)).length;
});

/** 监听收藏数量变化，同步更新 Logging 中的数量 */
watch(actualFavoriteCount, (newCount: number) => {
  logging.updateFavoriteCount(newCount);
});

async function fetchBorrows() {
  if (logging.getUser) {
    try {
      const response = await axios.get<ResultContext<BorrowRecord[]>>(
        `http://localhost:8080/api/users/${user.value?.id}/borrows`,
      );
      borrows.value = response.data.data;
    } catch (_error) {
      ElMessage.error("查询记录失败。");
    }
  }
}

async function fetchFavorites() {
  if (logging.getUser) {
    try {
      const response = await axios.get<ResultContext<FavoriteRecord[]>>(
        `http://localhost:8080/api/users/${user.value?.id}/favorites`,
      );
      favorites.value = response.data.data;
      // 初始化时同步更新 Logging 中的收藏数量
      logging.updateFavoriteCount(favorites.value.length);
    } catch (_error) {
      ElMessage.error("查询收藏记录失败。");
    }
  }
}

async function onFavoriteButtonClicked(id: number) {
  try {
    const response = await axios.patch<ResultContext<boolean>>(
      `http://localhost:8080/api/favorites/${id}`,
    );

    // 根据后端返回的状态更新本地收藏状态
    const newFavoriteState = response.data.data;

    // 更新本地状态映射
    localFavoriteStatus.value.set(id, newFavoriteState);

    // 弹出提示消息
    ElMessage({
      message: newFavoriteState ? "已收藏该图书" : "已取消收藏",
      type: newFavoriteState ? "success" : "info",
    });
  } catch (_error) {
    ElMessage.error("操作失败，请稍后重试");
  }
}

onMounted(() => {
  void fetchBorrows();
  void fetchFavorites();
});
</script>

<template>
  <div class="personal-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>个人中心</h1>
      <p>管理您的账户信息和图书借阅记录</p>
    </div>

    <!-- 基本信息卡片 -->
    <div class="info-card">
      <div class="card-header">
        <div class="user-avatar">
          <div class="avatar-circle">
            {{ logging.getUser?.nickname?.charAt(0) || "U" }}
          </div>
        </div>
        <div class="user-info">
          <h2 class="user-name">{{ displayName }}</h2>
          <p class="username" v-if="displayUsername">{{ displayUsername }}</p>
          <div class="user-details">
            <div class="detail-item">
              <span class="detail-label">注册时间:</span>
              <span class="detail-value"
                >{{
                  new Date(logging.getUser?.createTime!).toLocaleDateString(
                    "zh-CN",
                  ) || ""
                }}
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">会员状态:</span>
              <span
                class="detail-value"
                :class="{ 'member-badge': isMember, 'normal-badge': !isMember }"
              >
                {{ isMember ? "会员" : "普通用户" }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 借阅图书列表 -->
    <div class="section-card">
      <div class="section-header">
        <h3>已借阅</h3>
        <span class="section-count">{{ activeBorrows.length }} 本</span>
      </div>
      <div class="books-grid" v-if="activeBorrows.length > 0">
        <div
          v-for="record in activeBorrows"
          :key="record.id"
          class="book-item"
          :class="{ overdue: record.status === 'OVERDUE' }"
          @click="router.push(`/details/${record.book.id}`)"
        >
          <div class="book-info">
            <h4 class="book-title">{{ record.book.title }}</h4>
            <p class="book-author">{{ record.book.author }}</p>
            <div class="book-dates">
              <span class="borrow-date">借阅: {{ record.borrowTime }}</span>
              <span class="due-date">到期: {{ record.deadline }}</span>
            </div>
          </div>
          <div
            class="book-status"
            :class="
              record.status === 'OVERDUE' ? 'overdue-status' : 'normal-status'
            "
          >
            {{ BorrowStatusTitle[record.status] }}
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <p>暂无借阅图书</p>
      </div>
    </div>

    <!-- 收藏图书列表 -->
    <div class="section-card">
      <div class="section-header">
        <h3>收藏夹</h3>
        <span class="section-count">{{ actualFavoriteCount }} 本</span>
      </div>
      <div class="books-grid" v-if="favorites.length > 0">
        <div
          v-for="record in favorites"
          :key="record.id"
          class="book-item favorite-item"
          @click="router.push(`/details/${record.book.id}`)"
        >
          <div class="book-info">
            <h4 class="book-title">{{ record.book.title }}</h4>
            <p class="book-author">{{ record.book.author }}</p>
            <div class="book-dates">
              <span class="add-date">收藏于: {{ record.createTime }}</span>
            </div>
          </div>
          <div class="favorite-icon">
            <ElButton
              circle
              plain
              @click.stop="onFavoriteButtonClicked(record.id)"
            >
              <template #icon>
                <ElIcon size="24">
                  <StarFilled v-if="isFavorited(record.id)" />
                  <Star v-else />
                </ElIcon>
              </template>
            </ElButton>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <p>暂无收藏图书</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.personal-container {
  min-height: 100vh;
  padding: 24px;
  background: #f8f9fa;
}

.page-header {
  text-align: center;
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 600;
  color: #333;
}

.page-header p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.info-card {
  background: white;
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 24px;
}

.user-avatar {
  flex-shrink: 0;
}

.avatar-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff 0%, #53c0ff 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.user-info {
  flex: 1;
}

.user-name {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.username {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #666;
  font-weight: 400;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-label {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.detail-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.member-badge {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.normal-badge {
  background: #f0f0f0;
  color: #666;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.section-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.section-count {
  background: #409eff;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.book-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  cursor: pointer;
}

.book-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.book-item.overdue {
  border-color: #f56c6c;
  background: #fef0f0;
}

.book-info {
  flex: 1;
}

.book-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.book-author {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
}

.book-dates {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.borrow-date,
.due-date,
.add-date {
  font-size: 12px;
  color: #999;
}

.due-date {
  color: #f56c6c;
  font-weight: 500;
}

.book-status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
}

.normal-status {
  background: #e1f3d8;
  color: #67c23a;
}

.overdue-status {
  background: #fde2e2;
  color: #f56c6c;
}

.favorite-item {
  background: #f8f9fa;
  border-color: #e9ecef;
  position: relative;
  overflow: hidden;
}

.favorite-item::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: #ffa940;
  border-radius: 12px 12px 0 0;
}

.favorite-item:hover {
  border-color: #ffa940;
}

.favorite-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12px;
  padding: 0;
}

.favorite-icon .el-button {
  width: 32px;
  height: 32px;
  border: 1px solid #ffa940;
  color: #fa8c16;
  background: #fff;
  transition: all 0.2s ease;
}

.favorite-icon .el-button:hover {
  border-color: #ff7a00;
  background: #fff9f0;
  color: #ff7a00;
}

.favorite-icon .el-button:active {
  transform: scale(0.95);
}

.favorite-icon .el-icon {
  font-size: 16px;
  transition: all 0.2s ease;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .personal-container {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .books-grid {
    grid-template-columns: 1fr;
  }

  .book-item {
    flex-direction: column;
    gap: 12px;
  }

  .book-status {
    align-self: flex-start;
  }

  .favorite-icon {
    margin-left: 0;
    align-self: flex-start;
  }
}
</style>
